<?php
namespace Client\Controller;

use Client\Common\WechatHelper;
use Zend\Db\Sql\Expression;
use Client\Model\User;
use Client\Exception\ClientException;
use Client\Common\LoggerHelper;

class WechatController extends InitializeController
{   
    private $token = 'wechat';
    public static $app_id = 'wx5cd712847eff66e7';
    public static $app_secret = 'd10baba63897aa01755a5cf01c6d88d4';
    
    /*
     * 个人中心首页
     */
    public function indexAction()
    {
        $this->valid();
    }

    public function validAction()
    {
        //此代码只在微信公众号，认证服务器配置URL时使用。
        /*$echoStr = $_GET["echostr"];
        
        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }*/
   
    }
    
    public function wechatLoginAction()
    {       
        $testmode = $this->getConfigSys()['testmode'];

        if($testmode){
            return $this->redirect()->toUrl('/wechat/auth?testmode=1');
        }
        // 第一步：用户同意授权，获取code
        $state = 'redirect';
        $base_url = 'http://'.$_SERVER['HTTP_HOST'];
        $app_id = self::$app_id;
        $url = $base_url.'/wechat/auth';
        $url_encode = urlencode($url);
        return $this->redirect()->toUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$app_id."&redirect_uri=".$url_encode."&response_type=code&scope=snsapi_userinfo&state=".$state."#wechat_redirect");
    }
    
    //事务
    public function authAction(){
        $request = $this->getRequest();
        $testmode = $request->getQuery('testmode');
        $code = $request->getQuery('code');
        $state = $request->getQuery('state');
        if($testmode)
        {
            $state = 'redirect';
            $open_id = 'ol3D7wZKcgcyTKRVqsRuRmFz4Q3s';
            $user = $this->getUserTable()->getByOpenId($open_id);
        }else{
            
            // 第二步：通过code换取网页授权access_token
            $data_array = array(
                'code' => $code,
                'app_id' => self::$app_id,
                'app_secret' => self::$app_secret
        
            );
            $wechat_helper = new WechatHelper();
            $wechat_result = $wechat_helper->getWechatInfo($data_array);
            
            //获取UnionID
            if (empty($wechat_result['unionid'])) {
                $union_id = "";
            } else {
                $union_id = $wechat_result['unionid'];
            }
            $open_id = $wechat_result['openid'];
              
            //第三步：拉取用户信息(需scope为 snsapi_userinfo)
            $data_array = array(
                'open_id' => $wechat_result['openid'],
                'access_token' => $wechat_result['access_token'],
            );
            $wechat_userinfo = $wechat_helper->getWechatUserInfo($data_array);        
            
            
            $db = $this->getAdapter()->getDriver()->getConnection();
            $db->beginTransaction();
            try
            {           
                $user = $this->getUserTable()->getByOpenId($open_id);
                if (empty($user)) {
                    //注册用户
                    $set = array(
                        'open_id' => $open_id,
                        'union_id' => $union_id,
                        'sex' => $wechat_userinfo['sex'],
                        'user_thumb_image' => $wechat_userinfo['headimgurl'],
                        'user_name' => $wechat_userinfo['nickname'],
                        'user_create_time' => new Expression("NOW()")
                    );
                    $this->getUserTable()->insert($set);
                    $user_id = $this->getUserTable()->lastInsertValue;           
                    $user = $this->getUserTable()->getById($user_id);
                    $user->user_id = $user_id;
                    User::createUid($user);
                    $user->save();
                }
                $db->commit();
            }
            catch(\Exception $e)
            {
                $db->rollBack();
                LoggerHelper::client_exception($e);
                throw new ClientException('4001');
            }
        }
        
        $this->userLogin($user);
   
        if('redirect' == $state){
            
            if (!empty($_SESSION['redirect_uri'])) {
                //跳回原来请求页面
                $redirect_uri = $_SESSION['redirect_uri'];
                unset($_SESSION['redirect_uri']);
                return $this->redirect()->toUrl($redirect_uri);
            } else {  
                //跳回个人中心首页
                return $this->redirect()->toRoute('my', array(
                    'action' => 'home',
                ));
            }
        }
        echo 'error';
        exit;
    }
    
    /**
     * @param union_id
     * @param open_id
     * @param wechat_userinfo
     */private function userLogin($user)
    {
        //登入
        $_SESSION['user'] = array(
            'user_uid' => $user['user_uid'],
            'user_id' => $user['user_id'],
        );    
    }  
          
    private function checkSignature()
    {
    
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
    
        $token = $this->token;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
    
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}